import 'dart:io';

import 'package:flutter/material.dart';
import 'package:android_intent/android_intent.dart';
import 'package:grasp_flutter_app/page/bill_xsck_page.dart';
import 'package:grasp_flutter_app/utils/view/BottomNavigationBarEx.dart';
import '../utils/utils.dart';
import 'bill_page.dart';
import 'empty_page.dart';
import 'me_page.dart';

/// 主页
class MainPage extends StatefulWidget {
  static final String name = "main";

  @override
  State<StatefulWidget> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin {
  PageTabs tabs;
  int _currentIndex = 0;
  int _buildRef = 0;
  bool _selectMode = false;

  /// 不退出
  Future<bool> _dialogExitApp(BuildContext context) async {
    /// 如果是 android 回到桌面
    if (Platform.isAndroid) {
      AndroidIntent intent = AndroidIntent(
        action: 'android.intent.action.MAIN',
        category: "android.intent.category.HOME",
      );
      await intent.launch();
    }

    return false;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    if (tabs != null) {
      if (tabs.controller != null)
        tabs.controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (Consts.debug) print("build main ${_buildRef++}");
    if (tabs == null) {
        tabs = PageTabs(
            pageController: PageController(),
            tabViewDelegate: SliverChildBuilderDelegate((context, index) {
              return buildTabViewItem(context, index);
            }, childCount: 4),
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
                if (index > 1) _currentIndex++;
              });
            }
        );
    }

    return WillPopScope(
      onWillPop: () {
        return _dialogExitApp(context);
      },
      child: Stack(
        children: <Widget>[
          Common.buildBottomScaffold(
            context,
            tabs: tabs,
            bottomNavigationBar:Offstage(child: buildBottomNavBar(context, tabs), offstage: _selectMode),
          ),
          Container(
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(bottom: 35.0),
            child: _selectMode ? null : buildAddIocn(context),
          )
        ],
      ),
    );
  }

  /// 记录 PageView 中的页面, 防止每次切换都新建
  final List<Widget> pages = [null, null, null, null, null];

  Widget buildTabViewItem(BuildContext context, int index) {
    if (pages[index] != null) {
      if (Consts.debug) print("buildTabViewItem use cacle");
      return pages[index];
    }
    switch (index) {
      case 2:
        pages[index] = BillPage(onModeChange: (value) {
          setState(() {
            _selectMode = value;
          });
        });
        break;
      case 3:
        pages[index] = MePage();
        break;
      default:
        return EmptyPage(title: "Page $index");
    }
    return pages[index];
  }

  Widget buildBottomNavBar(BuildContext context, PageTabs tabs) {
    return new BottomNavigationBarEx(
      items:
      [
        BottomNavigationBarExItem(icon: Icon(Icons.home), title: buildTabItemTitle(Utils.getLocale(context).home, 0)),
        BottomNavigationBarExItem(icon: Icon(Icons.people), title: buildTabItemTitle(Utils.getLocale(context).commodity, 1)),
        BottomNavigationBarExItem(icon: Container(
            height: 46.0,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(bottom: 8.0),
            child: buildTabItemTitle(Utils.getLocale(context).newBill_XSCKD, 2))),
        BottomNavigationBarExItem(icon: Icon(Icons.donut_large), title: buildTabItemTitle(Utils.getLocale(context).bill, 3)),
        BottomNavigationBarExItem(icon: Icon(Icons.person), title: buildTabItemTitle(Utils.getLocale(context).me, 4)),
      ],
      currentIndex: _currentIndex,
      elevation: 4.0,
      space: 4.0,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) {
        if (_currentIndex == index) return;
        setState(() {
          if (index > 2) index--;
          tabs.pageController?.jumpTo(MediaQuery.of(context).size.width * index);
        });
      },
      // fixedColor: Styles.fontColorBottomBar,
    );
  }

  Widget buildTabItemTitle(String title, int index) {
    return Text(title, style: _currentIndex == index ? Styles.minPrimaryText : Styles.minSubText, textAlign: TextAlign.center);
  }

  Widget buildAddIocn(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        doAddBill();
      },
      //mini: true,
      isExtended: true,
      elevation: 4.0,
      child: const Icon(Icons.add, size: 36.0),
      backgroundColor: Styles.primaryValue,
    );
  }

  doAddBill() async {
    await Utils.startPageWait(context, BillXSCKPage());
  }
}